package test4.withLock;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

/**
 * @author 天启
 * @date 2020-02-19 16:31
 * @description 账户排序
 */
@AllArgsConstructor
public class Account {

    private Integer id;
    @Getter
    @Setter
    private String name;
    private int balance;

    /**
     * 转账
     *
     * @param target  目标
     * @param ammount 金额
     */
    void transferTo(Account target, int ammount) {
        // 锁定序号小的账户
        synchronized (this) {
            System.out.println("获得" + this.getName() + "的锁");
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                System.out.println("Thread for " + this.getName() + "sleep interrupted");
            }
            // 锁定序号大的账户
            synchronized (target) {
                System.out.println("获得" + target.getName() + "的锁");
                if (this.balance > ammount) {
                    this.balance -= ammount;
                    target.balance += ammount;
                }
            }
        }
    }
}